package com.itheima.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.User_managementDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.User;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
* 用户服务
* */
@Service(interfaceClass = User_managementService.class)
@Transactional
public class User_managementServiceImpl implements User_managementService{
    //注入DAO对象
    @Autowired
    private  User_managementDao user_managementDao;
    public void add(User user, Integer[] roles) {
        user_managementDao.add(user);
        Integer userId = user.getId();
        this.setUserAndRole(userId,roles);
    }

    //用户分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = user_managementDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<User> rows = page.getResult();
        return new PageResult(total,rows);
    }
    //根据ID删除检查项
    public void deleteById(Integer id) {
        user_managementDao.deleteAssocication(id);
        user_managementDao.deleteById(id);
    }
    //编辑用户关联角色
    public void edit(User user,Integer[] roles) {
        user_managementDao.edit(user);
        user_managementDao.deleteAssocication(user.getId());
        Integer userId = user.getId();
        this.setUserAndRole(userId,roles);
    }
    //建立用户和角色多对多关系
    public void setUserAndRole(Integer userId,Integer[] roles){
        if(roles !=null && roles.length>0){
            for(Integer role : roles){
                Map<String,Integer> map = new HashMap<>();
                map.put("userId",userId);
                map.put("role",role);
                user_managementDao.setUserAndRole(map);
            }
        }
    }

    public User findById(Integer id) {
        return user_managementDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return user_managementDao.findRoleIdsByUserId(id);
    }
}
